package com.moshang.blog.core.aop;

import com.alibaba.fastjson.JSONObject;
import com.moshang.blog.core.constant.CurrentUser;
import com.moshang.blog.entity.SysLog;
import com.moshang.blog.mapper.SysLogMapper;
import com.moshang.blog.core.utils.ToolUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * @program: blog
 * @description: 使用AOP统一处理Web请求日志
 * @author: xieweiwei
 * @create: 2018-09-25 18:33
 **/
@Aspect
@Component
public class WebControllerAop {
    @Autowired
    private SysLogMapper sysLogMapper;
    private static final Logger log = LoggerFactory.getLogger(WebControllerAop.class);
    /**
     * 指定切点
     * 匹配 com.moshang.blog.controller包及其子包下的所有类的所有方法
     */
    @Pointcut("@annotation(com.moshang.blog.core.annotation.SystemLog)")
    public void webLog(){
    }
    private SysLog sysLog = null;
    /**
     * 前置通知，方法调用前被调用
     * @param joinPoint
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint){
        System.out.println("我是前置通知!!!");
        //获取目标方法的参数信息
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
//        //代理的是哪一个方法
//        System.out.println("方法："+signature.getName());
//        //AOP代理类的名字
//        System.out.println("方法所在包:"+signature.getDeclaringTypeName());
        //AOP代理类的类（class）信息
        signature.getDeclaringType();
        MethodSignature methodSignature = (MethodSignature) signature;
        String[] strings = methodSignature.getParameterNames();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = (HttpSession) attributes.resolveReference(RequestAttributes.REFERENCE_SESSION);
        sysLog = new SysLog();
        sysLog.setClassMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        sysLog.setHttpMethod(request.getMethod());
        for (int i = 0; i < args.length; i++) {
            Object o = args[i];
            if(o instanceof ServletRequest || (o instanceof ServletResponse) || o instanceof MultipartFile){
                args[i] = o.toString();
            }
        }
        String str = JSONObject.toJSONString(args);
        sysLog.setParams(str.length()>5000?JSONObject.toJSONString("请求参数数据过长不与显示"):str);
        sysLog.setParams(Arrays.toString(strings));
        String ip = ToolUtil.getClientIp(request);
        if("0.0.0.0".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip) || "localhost".equals(ip) || "127.0.0.1".equals(ip)){
            ip = "127.0.0.1";
        }
        sysLog.setRemoteAddr(ip);
        sysLog.setRequestUri(request.getRequestURL().toString());
        if(session != null){
            sysLog.setSessionId(session.getId());
        }
        Method method = methodSignature.getMethod();
        com.moshang.blog.core.annotation.SystemLog systemLog = method.getAnnotation(com.moshang.blog.core.annotation.SystemLog.class);
        if(systemLog != null){
            //注解上的描述
            sysLog.setTitle(systemLog.value());
        }
        Map<String,String> browserMap = ToolUtil.getOsAndBrowserInfo(request);
        sysLog.setBrowser(browserMap.get("os")+"-"+browserMap.get("browser"));
        sysLog.setType(ToolUtil.isAjax(request)?"Ajax请求":"普通请求");
        sysLog.setIsActivited(0);
//        System.out.println("参数名："+ Arrays.toString(strings));
//        System.out.println("参数值ARGS : " + Arrays.toString(joinPoint.getArgs()));
//        // 接收到请求，记录请求内容
//        // 记录下请求内容
//        System.out.println("请求URL : " + request.getRequestURL().toString());
//        System.out.println("HTTP_METHOD : " + request.getMethod());
//        System.out.println("IP : " + request.getRemoteAddr());
//        System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

    }

    /**
     * 处理完请求返回内容
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Exception {
        String retString = JSONObject.toJSONString(ret);
        sysLog.setResponse(retString.length()>5000?JSONObject.toJSONString("请求参数数据过长不与显示"):retString);
        CurrentUser currentUser= (CurrentUser) SecurityUtils.getSubject().getPrincipal();
        if(currentUser != null) {
            sysLog.setUsername(StringUtils.isNotBlank(currentUser.getUserName()) ? currentUser.getUserName() :currentUser.getRealName());
            sysLog.setCreateBy(currentUser.getId());
            sysLog.setUpdateBy(currentUser.getId());
            sysLog.setCreateName(currentUser.getUserName());
            sysLog.setUpdateName(currentUser.getUserName());
        }
        sysLog.setCreateTime(new Date());
        sysLog.setUpdateTime(new Date());

        sysLogMapper.insert(sysLog);
//        // 处理完请求，返回内容
//        System.out.println("方法的返回值 : " + ret);
    }

    /**
     * 后置异常通知
     * @param jp
     */
    @AfterThrowing("webLog()")
    public void throwss(JoinPoint jp){
        System.out.println("方法异常时执行.....");
    }

    /**
     * 后置最终通知,final增强，不管是抛出异常或者正常退出都会执行
     * @param jp
     */
    @After("webLog()")
    public void after(JoinPoint jp){

    }

    /**
     * 环绕通知,环绕增强，相当于MethodInterceptor
     * @param pjp
     * @return
     */
    @Around("webLog()")
    public Object arround(ProceedingJoinPoint pjp) {
        try {
            Object o =  pjp.proceed();
            return o;
        } catch (Throwable e) {
            sysLog.setException(e.getMessage());
            e.printStackTrace();
            return null;
        }
    }


}
